<?php
/**
 * Created by PhpStorm.
 * User: geolo
 * Date: 2018/9/5
 * Time: 15:59
 */
namespace app\modules\mch\models;
use app\models\LiveActor;
class LiveActorForm extends Model
{

    public $actor_name; // 小程序id
    public $actor_secret;
    public $wechat_app_id;

    public function rules()
    {
        return [
            [['actor_name'], 'trim'],
            [['wechat_app_id','actor_name'], 'required'],
        ];
    }

    public function attributeLabels()
    {
        return [
            'wechat_app_id'=>'请先申请小程序',
            'actor_name' => '请填写用户名',

        ];
    }

    public function save()
    {
        if (!$this->validate())
            return $this->getModelError();
        $model = new LiveActor();
        $model->attributes = $this->attributes;
        $model->wechat_app_id = $this->wechat_app_id;
//        $data = $this->attributes;
//        var_dump($data);
        $connection = \Yii::$app->db;
        $command = $connection->createCommand('SELECT count(*)as rcount FROM hjmall_actor where wechat_app_id='.$this->wechat_app_id.'');
        $num = $command->queryOne();
//        var_dump($num);
        if($num['rcount']<=0) {
            if ($model->save()) {
                return [
                    'code' => 0,
                    'msg' => '保存成功',
                ];
            }
        }else{
            $upd = LiveActor::findOne(['wechat_app_id'=>$this->wechat_app_id]);
            $upd->actor_name = $this->actor_name;
            $upd->actor_secret = $this->actor_secret;
            if($upd->save()){
                return [
                    'code' => 0,
                    'msg' => '保存成功',
                ];
            }
        }
        return $this->getModelError($model);
    }

}

